import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import TicketTable from './TicketTable';
import TauTable from '@/components/TauTable';
import styles from './BusOrderForm.module.scss';
import ReceiptDialog from './ReceiptDialog';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

function BusOrderForm({ orderId, modal, onSubmit, onCancel }) {
  const { busOrderStore: store } = useStore();
  const [order, setOrder] = useState();
  const [busOrders, setBusOrders] = useState([]);
  const [isViewMode] = useState(modal[0] === 'view');
  const [oldOrder, setOldOrder] = useState();
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [receiptDialog, setReceiptDialog] = useState(null);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const data = await store.get(orderId);
      setBusOrders([data]);
      if (data?.changeAssociatedOrderIds) {
        const allOrder = await store.getChangeOrder(data?.changeAssociatedOrderIds);
        const old = allOrder.filter((p) => !p.changeAssociatedOrderIds);
        setOldOrder(old[0] || null);
        const filter = allOrder.filter((p) => p.changeAssociatedOrderIds).filter((p) => p.busOrder.orderStatus !== 4);
        setBusOrders(filter);
      }
      editCtx.origin = _.cloneDeep(data);
      setOrder(toJS(data));
    })();
  }, []);

  if (!order) return <></>;

  const overrideModel = {
    discountInfos: {
      ui: {
        renderer: (v) => {
          return (
            <TauTable
              dataSource={v}
              primaryKey="couponId"
              hidePagination
              hasBorder={false}
              className={styles.discountInfos_table}
              columns={[
                { title: '活动名称', dataIndex: 'activityName' },
                { title: '活动Id', dataIndex: 'activityId' },
                { title: '优惠券名称', dataIndex: 'couponName' },
                { title: '优惠券Id', dataIndex: 'couponId' },
                { title: '优惠券金额', dataIndex: 'discountPrice' },
                { title: '优惠券成本', dataIndex: 'cost' },
              ]}
            />
          );
        },
      },
    },
    oldChangePrice: {
      ui: {
        renderer: () => {
          const { originalPrice, price } = oldOrder || {};
          return <span>{t`${originalPrice?.toFixed(2) || (price || 0).toFixed(2)} / ${(price || 0).toFixed(2)}`}</span>;
        },
      },
    },
    busOrder: {
      orderId: {
        ui_view: {
          renderer: (v, r) => {
            const { companyId } = r?.busOrder;
            let value = null;
            const isZL = global.getEnvCfg()?.companies?.ZL?.id == companyId;
            value = (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span>{v}</span>
                {isZL && <Button text type="primary" style={{ marginLeft: 5 }} onClick={() => handleViewReceipt(r)}>{t`( 查看发票 )`}</Button>}
              </div>);
            return value;
          },
        },
      },
    },
  };

  const handleViewReceipt = async (record) => {
    setReceiptDialog({
      show: true,
      record,
    });
  };

  const receiptOncancel = () => {
    setReceiptDialog({
      show: false,
      record: null,
    });
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(order, name, value);
    setOrder({ ...order });

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    if (!_.isEmpty(editCtx.changed)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={order}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={order}
        mode="view"
        overrideModel={overrideModel}
        fields={['orderNumber', 'busOrder.collectorName', 'busOrder.collectorPhone', 'busOrder.fullname',
          'busOrder.orderStatus', 'busOrder.companyName', 'crDate', 'busOrder.phone',
          'source', 'attributionName', 'receiveName', 'busOrder.payType', 'busOrder.payTime', 'busOrder.isRoundTrip',
          'price', 'discountPriceTotal', 'busOrder.orderId'].concat(oldOrder ? ['oldChangePrice'] : [])}
      />
      <TitleGrid title={t`优惠信息`} />
      <FieldsGrid
        formData={order}
        mode="view"
        overrideModel={overrideModel}
        fields={['discountInfos']}
      />
      {busOrders.map((item) => {
        const { busOrder } = item;
        return (
          <>
            <TitleGrid title={t`预订信息`} />
            <FieldsGrid
              formData={item}
              mode="view"
              fields={['orderNumber', 'subPrice']}
            />
            <FieldsGrid
              formData={item}
              mode="view"
              fields={['from.stationName', 'from.onAddress', 'shift.date',
                'to.stationName', 'to.offAddress', 'shift.scheduledShiftTime'].map((p) => `busOrder.${p}`)}
            />
            {busOrder.isRoundTrip && <br />}
            {busOrder.isRoundTrip &&
              <FieldsGrid
                formData={item}
                mode="view"
                fields={['returnFrom.stationName', 'returnFrom.onAddress', 'returnShift.date',
                  'returnTo.stationName', 'returnTo.offAddress', 'returnShift.scheduledShiftTime'].map((p) => `busOrder.${p}`)}
              />
            }
            <TitleGrid title={t`乘客信息`} />
            <ResponsiveGrid gap={[0, 24]} columns={4}>
              <Cell colSpan={12}>
                <TicketTable
                  busOrder={busOrder}
                  changeAssociatedOrderId={item?.changeAssociatedOrderId}
                  inForm
                  orderId={item.id}
                  isViewMode={isViewMode}
                />
              </Cell>
            </ResponsiveGrid>
          </>
        );
      })}

      <TitleGrid title={t`其他`} />
      <FieldsGrid
        formData={order}
        mode="view"
        fields={['busOrder.remarks']}
      />
      <FieldsGrid
        formData={order}
        mode={modal[0] === 'view' ? 'view' : 'edit'}
        fields={['busOrder.consoleRemarks']}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={() => onSubmit(order)}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <ReceiptDialog dialog={receiptDialog} onCancel={receiptOncancel} />
    </Form>
  );
}

export default BusOrderForm;

